<?php
class MobileAuth extends AppModel {

    public $useTable = false;
    private $api = 'http://106.ihuyi.cn/webservice/sms.php';
    const SESSION_MOBILE_CODE = 'mobile_code';
    private $api_account = 'cf_yunyao91';
    private $api_password = 'yy0391';

    function send($mobile){
        try {
            $mobile = trim($mobile);
            if(empty($mobile)){
                throw new Exception("手机号不能为空", 1);
            }
            if(!is_numeric($mobile)){
                throw new Exception("手机号必须是数字", 1);
            }
            if(strlen($mobile) != 11){
                throw new Exception("手机号错误", 1);
            }
            $mobile_code = $this->random(4,1);
            $str = "您的验证码是：{$mobile_code}。请不要把验证码泄露给其他人。如非本人操作，可不用理会！";
            // CakeLog::write('info', "[{$mobile}]".$str);
            $params = array(
                'method' => 'Submit',
                'account' => $this->api_account,
                'password' => $this->api_password,
                'mobile' => $mobile,
                'content' => $str
            );
            App::uses('Ivf', 'Lib');
            $res = Ivf::httpGet($this->api, $params, 30);
            $res = $this->xml_to_array($res);
            $logs = ClassRegistry::init('Log');
            $logs->addLog(json_encode($res),Ivf::getClientIp());
            if(isset($res['SubmitResult']['code']) && $res['SubmitResult']['code'] == '2'){
                $data['status'] = 'success';
            }else{
                throw new Exception($res['SubmitResult']['msg'], $res['SubmitResult']['code']);
            }
            $data['status'] = 'success';
            $data['code'] = $mobile_code;
        } catch (Exception $e) {
            $data['msg'] = $e->getMessage();
            $data['status'] = 'fail';
        }
        return $data;
    }

    function send_msg($mobile, $msg){
        try {
            $params = array(
                'method' => 'Submit',
                'account' => $this->api_account,
                'password' => $this->api_password,
                'mobile' => $mobile,
                'content' => $msg
            );
            App::uses('Ivf', 'Lib');
            $res = Ivf::httpGet($this->api, $params, 30);
            $res = $this->xml_to_array($res);
            $logs = ClassRegistry::init('Log');
            $logs->addLog("mobile:".$mobile.",content:".$msg.",api result:".json_encode($res),Ivf::getClientIp());
            if(isset($res['SubmitResult']['code']) && $res['SubmitResult']['code'] == '2'){
                $data['status'] = 'success';
            }else{
                throw new Exception($res['SubmitResult']['msg'], $res['SubmitResult']['code']);
            }
            $data['status'] = 'success';
        } catch (Exception $e) {
            $data['msg'] = $e->getMessage();
            $data['status'] = 'fail';
        }
        return $data;
    }

    private function random($length = 6 , $numeric = 0) {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }

    private function xml_to_array($xml){
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if(preg_match_all($reg, $xml, $matches)){
            $count = count($matches[0]);
            for($i = 0; $i < $count; $i++){
            $subxml= $matches[2][$i];
            $key = $matches[1][$i];
                if(preg_match( $reg, $subxml )){
                    $arr[$key] = $this->xml_to_array( $subxml );
                }else{
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }

}